package top.cn27.luckyhe.mirai.plugin.residence.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ConfigOperation {
    private static File configPath;
    private static String configFileName = "config.properties";

    public static void initConfigPath(File path, String configContent) throws IOException {
        configPath = path;

        File[] files = configPath.listFiles();
        boolean hasConfig = false;
        for (File file : files) {
            if (file.getName().equals(configFileName)) {
                hasConfig = true;
                break;
            }
        }
        if (!hasConfig) {
            copyConfigPathFromResource(configContent);
        }
    }

    private static void copyConfigPathFromResource(String configContent) throws IOException {
        FileOutputStream fos = new FileOutputStream(configPath.getPath() + "/" + configFileName);

        byte[] buf = configContent.getBytes(StandardCharsets.UTF_8);
        fos.write(buf);
        fos.close();
    }

    private static Properties getPropertiesFromFile() throws IOException {
        InputStream is = new BufferedInputStream(new FileInputStream(configPath.getPath() + "/" + configFileName));
        Properties p = new Properties();
        p.load(is);
        is.close();

        return p;
    }

    public static Map<String, String> getMySqlConnInfo() throws IOException {
        Properties p = getPropertiesFromFile();

        Map<String, String> resMap = new HashMap<>();
        resMap.put("url", p.getProperty("mysql.url"));
        resMap.put("username", p.getProperty("mysql.username"));
        resMap.put("password", p.getProperty("mysql.password"));

        return resMap;
    }

    public static Map<String, String> getRconConnInfo() throws IOException {
        Properties p = getPropertiesFromFile();

        Map<String, String> resMap = new HashMap<>();
        resMap.put("host", p.getProperty("rcon.host"));
        resMap.put("port", p.getProperty("rcon.port"));
        resMap.put("password", p.getProperty("rcon.password"));

        return resMap;
    }
}
